var DEBUGGER = false;
var AUTHORIZER_APPID = 'wx36bea992a3856d4a'; // mofa
// var AUTHORIZER_APPID = 'wx022ec8687b780a34'; // panx
var SDK_CONFIG_API = '/open-wechat/authorizer-js-sdk/';
var MAY_PROMO_CREATE = '/api/may-promo/create';
var GET_MEDIA_ID = '/api/may-promo/get-media-id';
var GET_PIC_URL = '/api/may-promo/get-pic-url'; // 请求化妆后的url

var may = new Vue({
    el: '#root',

    mixins:[mayPromoMixin],

    data: function () {
        return {
            openid: null, // openid
            user_info: null, // 用户数据
            current_media_id: null, // 媒体文件的 id;
            cosmetics: [], // 化妆素材,
            tencent_image: null,
            selected_cosmetic_id: null,
            can_lucky_draw: false, // 抽奖?
            page_title:'2D 美妆试妆',
            share_title:'魔镜魔镜告诉我',
            page_icon:'https://gz.bcebos.com/v1/beauty-mirror/may-promo/icon.png',
            is_visible_cover: true,
            is_show_share_tip: false, // false
            is_visible_error: false,
            error_tips:'试妆失败,请重新上传照片',
            picture_cache: { // 图像缓存

            }
        }
    },

    mounted: function() {
      var self = this;

      panxVConsole({left: '0px', bottom: '0px'});

      this.resolveOpenId()
        .then(function (openid){
          self.openid = openid;
          // 请求用户信息
          self.fetchUserInfo(openid)
            .then(function (user_info) {
              if (user_info) {
                self.user_info = user_info;
              }
            });

          self.fetchSdkConfig(AUTHORIZER_APPID);
          self.fetchCosmetics({openid: openid, appid: AUTHORIZER_APPID});
          self.handleFetchCouponIndex(openid);
        });
    },

    methods: {

        /**
         *  请求sdk 配置
         */
        fetchSdkConfig: function () {
            var self = this;

            var sdk_params = {
              target_url: location.href,
            };

            if (DEBUGGER) {
              sdk_params.debug = 1;
            }

            axios.post(SDK_CONFIG_API+ AUTHORIZER_APPID, sdk_params)
                .then(function (response) {
                    if (parseInt(response.data.code) !== 0) {
                        throw new Error(response.data.error)
                    } else {
                        self.initWxSdk(response.data.config);
                    }
                })
                .catch(function (error) {
                    console.log(error);
                })

        },

        /**
         *  初始化 wechat skd
         */
        initWxSdk: function (config) {
            // alert(config.signature);
            console.log('init sdk', config);
            
            wx.config(config);
            this.listenWechatSdkEvent();
        },

        /**
         *  监听 wechat sdk
         */
        listenWechatSdkEvent: function () {
            wx.ready(this.handleWxSdkReady);
            wx.error(this.handleWxSdkError);

            // 分享朋友圈
            wx.onMenuShareTimeline({
                title: this.share_title, // 分享标题
                link: location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: this.page_icon, // 分享图标
                success: this.handleShareTimeLineSuccess,
                cancel: this.handleShareTimeLineCancel,
                trigger: this.logMenuEvent
            });
        },

        logMenuEvent: function(event) {
          console.log(event);
        },

        /**
         * 处理sdk 错误
         * @param res
         */
        handleWxSdkError: function (res) {
            console.log(res);
        },

        /**
         * 处理 wx ready
         */
        handleWxSdkReady: function () {
            // alert('ready');
        },

        /**
         * 分类朋友圈
         */
        handleShareTimeLineSuccess: function () {
            location.href = '/may-promo/makeup-tryon/shake.html?v='+Math.random();
        },

        /**
         *  取消分享朋友圈
         */
        handleShareTimeLineCancel: function () {
            weui.alert('只有分享才能抽奖');
        },


        /**
         * 请求美妆素材
         * @params {string} params.openid
         * @params {string} params.appid
         */
        fetchCosmetics: function (params) {
            var self = this;
            axios.get(MAY_PROMO_CREATE,{params:params})
                .then(function (response) {
                    if (parseInt(response.data.code) !== 0) {
                        throw new Error(response.data.error)
                    } else {
                        self.cosmetics = response.data.cosmetics;
                        return response.data.cosmetics;
                    }
                })
                .then(function (cosmetics) {
                    if (cosmetics.length) { // 设置默认
                        self.selected_cosmetic_id = cosmetics[0].id;
                    }
                })
                .catch(function (error) {
                    console.log(error);
                })
        },

        /**
         *  处理图像文件 change
         */
        selectImageFile: function (event) {
            var self = this;
            wx.chooseImage({
                count: 1, // 默认9
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                    console.log('res',res);
                    self.uploadImage(localIds[0]);
                }
            });
        },

        /**
         *  上传 wx 图像
         */
        uploadImage: function (localId) {
            var self = this;
            wx.uploadImage({
                localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得
                isShowProgressTips: 1, // 默认为1，显示进度提示
                success: function (res) {
                    var serverId = res.serverId; // 返回图片的服务器端ID
                    self.current_media_id = serverId;
                    self.fetchTencentPictureUrl({
                        appid: AUTHORIZER_APPID,
                        openid: self.openid,
                        media_id: serverId,
                        id: self.selected_cosmetic_id,
                        // type: 'png'
                    });
                }
            });
        },

        /**
         * 创建 formdata 对象
         */
        createDataForm: function (form) {
            var fd = new FormData();
            for (var field in form) {
                fd.append(field, form[field]);
            }
            return fd;
        },


        /**
         *  提交图像并换取图像的id
         */
        postImageFile: function (form) {
            var self = this;
            axios.post(GET_MEDIA_ID, form)
                .then(function (response) {
                    self.current_media_id = response.data.media_id;
                    return response.data.media_id;
                })
                .then(function (media_id) {
                    self.fetchTencentPictureUrl({
                        appid: AUTHORIZER_APPID,
                        openid: self.openid,
                        media_id: media_id,
                        id: self.selected_cosmetic_id,
                        // type: 'png'
                    });
                })
                .catch(function (error) {
                    console.log(error);
                })
        },

        /**
         *  请求化妆后的url
         */
        fetchTencentPictureUrl: function (params) {
            var loading = weui.loading('马上好了');
            var self = this;
            var key = params.media_id+'#'+params.id;
            var cache = this.getPictureFromCache(key);
            if (cache) {
                this.tencent_image = cache;
                loading.hide();
                return;
            };
            axios.get(GET_PIC_URL, {params:params})
                .then(function (response) {
                    if(parseInt(response.data.code) !== 0) { //
                        throw new Error(response.data.error)
                    } else {
                        var ret = parseInt(response.data.tencent_image.ret);
                        if (ret !== 0) { // Tencent error
                            var msg = response.data.tencent_image.msg;
                            msg = (ret === 16402) ? '照片中找不到脸部,请重新上传': ('头像图片分析失败['+ret+']');
                            throw new Error(msg);
                        } else{
                            var base64 = 'data:image/jpeg;base64,'+response.data.tencent_image.data.image;
                            self.tencent_image = base64;
                            self.hideCover();
                            self.setPictureToCache(key, base64);
                        }
                    }
                })
                .catch(function (error) {
                    self.showErrorTips(error.message);
                    console.log(error);
                })
                .then(function () {
                    loading.hide();
                })
        },

        /**
         * 获取图片
         * @param key
         * @returns {*}
         */
        getPictureFromCache: function(key) {
            if (key in this.picture_cache) {
                return this.picture_cache[key];
            } else {
                return null;
            }
        },

        /**
         * 设置缓存
         * @param key
         * @param value
         */
        setPictureToCache: function(key, value){
            /**
            * 康林你需要仔细学习下操作符优先级
            *
            * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
            */
            if (! (key in this.picture_cache)) {
                this.picture_cache[key] = value;
            }
        },

        /**
         *  显示错误
         */
        showErrorTips: function(message, timer) {
            if (this.is_visible_error) {
                return ;
            }
            timer = timer || 1500;
            var self = this;
            this.error_tips = message;
            this.is_visible_error = true;
            window.setTimeout(function () {
                self.is_visible_error = false;
            },timer)
        },

        /**
         *  处理 素材 select
         */
        handleCosmeticsSelected: function (id, event) {
            this.selected_cosmetic_id = id;
            if (!this.current_media_id) return;
            this.fetchTencentPictureUrl({
                appid: AUTHORIZER_APPID,
                openid: this.openid,
                media_id: this.current_media_id,
                id: this.selected_cosmetic_id,
                // type: 'png'
            });
        },

        /**
         *  隐藏封面
         */
        hideCover: function () {
            this.is_visible_cover = false;
        },

        /**
         *  隐藏分享提示
         */
        hideShareTips: function () {
            this.is_show_share_tip = false;
        },

        /**
         * 请求卡券列表
         * @param openid
         */
        handleFetchCouponIndex(openid){
            var self = this;
            this.fetchCouponIndex({
                appid:AUTHORIZER_APPID ,
                openid:openid
            }).then(function (coupons) {
                if (coupons instanceof Array && coupons.length>0) {
                    self.hideShareTips();
                } else {
                    self.is_show_share_tip = true;
                }
            })

        },

        initVConsole() {
          new VConsole();
        }
    }
});

